package com.senseilearning.sensei;

import java.io.IOException;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;

public class XMLFileReader {
	private XmlPullParser xpp;
	private Context context;
	
	public XMLFileReader(Context context){
		this.context = context;
	}
	
	public void readChapters() {
		try {	
			if(Locale.getDefault().getLanguage().equals("nl")){
				System.out.println("test2");
				xpp = context.getResources().getXml(R.xml.data_nl);
			} else{
				xpp = context.getResources().getXml(R.xml.data);
			}
			while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
				if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("CHAPTER")) {
					Chapters.addChapter(readChapter());
				}
				
				xpp.next();
			}
		} catch (Throwable t) {
			//Toast.makeText(context, "Request failed: " + t.toString(), Toast.LENGTH_SHORT).show();
		}
	}

	private Chapter readChapter() throws XmlPullParserException, IOException {
		Chapter chapter = new Chapter();
		while (!(xpp.getEventType() == XmlPullParser.END_TAG && xpp.getName().equals("CHAPTER"))) {
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("CHAPTER_NAME")) {
				xpp.next();
				chapter.setName(xpp.getText());
			}
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("SECTION")) {
				chapter.addSection(readSection());
			}
			xpp.next();
		}
		return chapter;
	}

	private Section readSection() throws XmlPullParserException, IOException {
		Section section = new Section();
		while (!(xpp.getEventType() == XmlPullParser.END_TAG && xpp.getName().equals("SECTION"))) {
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("SECTION_NAME")) {
				xpp.next();
				section.setName(xpp.getText());
			}
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("WORD")) {
				section.addWord(readWord());
			}
			xpp.next();
		}
		return section;
	}

	private Word readWord() throws XmlPullParserException, IOException {
		Word word = new Word();
		while (!(xpp.getEventType() == XmlPullParser.END_TAG && xpp.getName().equals("WORD"))) {
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("W1")) {
				xpp.next();
				String tmp = xpp.getText();
				tmp = tmp.trim();
				word.setWord1(tmp);
			}
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("W2")) {
				xpp.next();
				String tmp = xpp.getText();
				tmp = tmp.trim();
				word.setWord2(tmp);
			}
			if (xpp.getEventType() == XmlPullParser.START_TAG && xpp.getName().equals("TAGS")) {
				xpp.next();
				word.addTags(xpp.getText());
			}
			xpp.next();
		}
		return word;
	}

	
}
